<template>
  <el-dialog
    v-model="isShowDialog"
    :before-close="handleClose"
    title="商品条码打印"
    draggable
    width="80%"
  >
    <div>
      <el-button type="danger" @click="batchDelete">删除所选</el-button>
    </div>
    <vxe-table
      ref="tablePrintRef"
      border
      :row-config="{ isCurrent: true, isHover: true }"
      style="margin-top: 10px"
      align="center"
      :data="tableData"
      height="400"
      :checkbox-config="{ trigger: 'row' }"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="seq" width="80" title="序号"></vxe-column>
      <vxe-column field="skuCode" width="200" title="云仓SKU编码"></vxe-column>
      <vxe-column field="skuName" width="300" title="商品名称"></vxe-column>
      <vxe-column field="coverUrl" width="180" title="商品图片">
        <template #default="{ row }">
          <ImagePreview
            v-if="row.coverUrl"
            :width="150"
            :height="50"
            :src="row.coverUrl"
          ></ImagePreview>
        </template>
      </vxe-column>
      <vxe-column
        field="classifyName"
        width="150"
        title="商品分类"
      ></vxe-column>
      <vxe-column field="attrName" width="120" title="属性"></vxe-column>
      <vxe-column field="price" width="80" title="售价¥"></vxe-column>
      <vxe-column width="150" title="打印数量">
        <template #header>
          <span>打印数量</span>
          <el-button
            style="margin-left: 20px"
            type="text"
            @click="clickBatchNum"
            >批下</el-button
          >
        </template>
        <template #default="{ row }">
          <el-input
            v-model="row.printNum"
            @input="row.printNum = limitIntNumber(row.printNum)"
            @change="changePrintNum"
            clearable
          />
        </template>
      </vxe-column>

      <vxe-column fixed="right" width="150" title="操作">
        <template #default="{ row }">
          <el-button type="text" style="color: green" @click="clickView(row)"
            >预览</el-button
          >
          <el-button type="text" style="color: red" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </vxe-column>
    </vxe-table>
    <div style="margin: 10px 0">
      <span
        >打印数量合计:
        <span style="font-size: 18px; color: red">{{
          printNumTotal
        }}</span></span
      >
      <span style="margin-left: 10px"
        >模板:
        <el-select
          style="width: 230px"
          v-model="printTemp"
          @change="changeTemp"
        >
          <template v-for="(item, index) in printTempList" :key="index">
            <el-option
              :label="item.configName"
              :value="item.printConfigId"
            ></el-option>
          </template>
        </el-select>
      </span>
      <span style="margin-left: 10px">
        打印机:
        <el-select
          v-model="printMachine"
          clearable
          placeholder="打印机"
          style="width: 300px"
        >
          <template v-for="(item, index) in printNameList" :key="index">
            <el-option :label="item" :value="item" />
          </template>
        </el-select>
      </span>
      <el-button style="margin-left: 10px" type="primary" @click="clickPrint"
        >打印</el-button
      >
      <el-button
        style="margin-left: 10px"
        type="primary"
        @click="clickPrintAndClose"
        >打印并返回</el-button
      >
    </div>

    <!--    打印区域-->
    <div style="display: none">
      <template v-for="(item, index) in printData" :key="index">
        <div :id="'printDiv' + item.skuId">
          <div style="width: 100%">
            <svg :id="'barcode' + item.skuId"></svg>
            <div style="font-size: 6pt; width: 90%; margin-left: 10px">
              <div class="skuFont">
                {{ item.skuName }},{{
                  item.attrName
                    ? Object.values(JSON.parse(item.attrName)).join("/")
                    : ""
                }}
                <!-- <span style="margin-left: 10px" v-if="tempStyle == '2'">{{
                  item.attrName
                }}</span> -->
                <div v-if="tempStyle == '3'">销售价格:{{ item.price }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted } from "vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import { getLodop } from "@/assets/LodopFuncs";
import { getPrintConfigList } from "@/api/scApi";
import JsBarcode from "jsbarcode";
import { limitIntNumber } from "@/utils/shuangcheng";
import { usePrintStore } from "@/store/modules/print";

const printStore = usePrintStore();

const { proxy } = getCurrentInstance();
const props = defineProps({
  isShowDialog: {
    type: Boolean,
    default: false,
  },
  title: { type: String },
  detailData: { type: Object },
  isView: { type: Boolean },
});
let tableData = ref([]);
let printTemp = ref(""); //打印模板
let printTempList = ref([]); //打印模板集合
let printMachine = ref(""); //打印机名称
let printNameList = ref([]);
let printData = ref([]); //打印的数据
let printNumTotal = ref(0); //打印数量合计
let tempStyle = ref(""); //模板样式
let LODOP;
onMounted(() => {
  tableData.value = props.detailData.map((item) => {
    item.printNum = 1;
    return item;
  });
  printNumTotal.value = tableData.value.length;

  setTimeout(() => {
    LODOP = getLodop();
    getPrinterCount();
  }, 500);

  getGoodsTempList();
  printStore.connect();
});

const emits = defineEmits(["cancel"]);

function handleClose() {
  emits("cancel");
}

//删除
function handleDelete(row) {
  tableData.value = tableData.value.filter((item) => item.skuId !== row.skuId);
}

//批下
function clickBatchNum() {
  tableData.value = tableData.value.map((item) => {
    item.printNum = tableData.value[0].printNum;
    return item;
  });
  changePrintNum();
}

//删除所选
function batchDelete() {
  const $table = proxy.$refs.tablePrintRef;
  if ($table) {
    const selectRecords = $table.getCheckboxRecords();
    if (selectRecords.length === 0) {
      proxy.$modal.msgWarning("请选择要删除的数据!");
    } else {
      tableData.value = tableData.value.filter(
        (item) => !selectRecords.some((selObj) => selObj.skuId === item.skuId)
      );
    }
  }
}

//获取打印机
function getPrinterCount() {
  LODOP = getLodop();
  if (LODOP) {
    //获取打印机个数
    let printNum = LODOP.GET_PRINTER_COUNT();
    for (let i = 0; i < printNum; i++) {
      printNameList.value.push(LODOP.GET_PRINTER_NAME(i));
    }
  }
}
//预览
function clickView(row) {
  printData.value = [row];
  printFunc(row);
}
function clickPrint() {
  printData.value = tableData.value;
  let num = 0;
  for (let i = 0; i < tableData.value.length; i++) {
    num++;
    let printObj = tableData.value[i];
    if (printObj.printNum && printObj.printNum * 1 > 1) {
      //同一个商品条码打印多次
      for (let j = 0; j < printObj.printNum * 1; j++) {
        surePrint(printObj);
        // printFunc(printObj, true);
      }
    } else {
      surePrint(printObj);
      // printFunc(printObj, true);
    }
  }
}

//打印并关闭
function clickPrintAndClose() {
  clickPrint();
  setTimeout(() => {
    handleClose();
  }, 1000);
}
//打印方法
function printFunc(printData, isPrint) {
  nextTick(() => {
    JsBarcode("#barcode" + printData.skuId, printData.skuCode, {
      fontSize: 28,
      fontOptions: "bold",
      displayValue: true, //是否在条形码下方显示文字
    });
    let tempData = printTempList.value.filter(
      (temp) => temp.printConfigId === printTemp.value
    )[0]; //获取模板数据
    //根据纸张大小控制 条码大小
    document.querySelector("#barcode" + printData.skuId).style.width =
      tempData.width * 0.9 + "mm";
    document.querySelector("#barcode" + printData.skuId).style.height =
      tempData.height * 0.4 + "mm";
    //根据纸张大小 控制字体大小
    if (tempData.height * 1 >= 40) {
      document.querySelector(".skuFont").style.fontSize = "10pt";
    } else {
      document.querySelector(".skuFont").style.fontSize = "6pt";
    }

    let strFormHtml = document.querySelector(
      "#printDiv" + printData.skuId
    ).innerHTML;
    LODOP.PRINT_INIT(""); //初始化
    LODOP.SET_PRINT_PAGESIZE(1, tempData.width * 10, tempData.height * 10); //设置纸张大小
    LODOP.ADD_PRINT_HTM("1%", "1%", "98%", "98%", strFormHtml); //设置打印内容
    LODOP.SET_PRINTER_INDEX(printMachine.value); //设置打印机
    if (isPrint) {
      LODOP.PRINT();
    } else {
      LODOP.PREVIEW();
    }
  });
}
//获取商品模板
function getGoodsTempList() {
  let params = {
    pageSize: 0,
    param: { printType: 0, statusSort: true },
  };
  getPrintConfigList(params).then((res) => {
    if (res.code === 200) {
      printTempList.value = res.data;
      //设置默认模板 和默认打印机,样式
      printTemp.value = res.data[0].printConfigId;
      printMachine.value = res.data[0].printMachine;
      let tempData = printTempList.value.filter(
        (temp) => temp.printConfigId === printTemp.value
      )[0]; //获取模板数据
      tempStyle.value = tempData.printStyle;
    }
  });
}

function changePrintNum() {
  printNumTotal.value = 0;
  tableData.value.map((item) => {
    printNumTotal.value += item.printNum * 1;
  });
}

//选择模板
function changeTemp() {
  let tempData = printTempList.value.filter(
    (temp) => temp.printConfigId === printTemp.value
  )[0]; //获取模板数据
  tempStyle.value = tempData.printStyle;
}

async function surePrint(data) {
  const printObj = {
    data: {
      qrCode: data.skuCode,
      skuCode: data.skuCode,
      goodName: data.skuName,
      price: data.tagPrice,
    },
    templateURL: "https://cloudprint.cainiao.com/template/standard/751202/15",
  };
  const taskID = printStore.getUUID(8, 10);
  let tempData = printTempList.value.filter(
    (temp) => temp.printConfigId === printTemp.value
  )[0]; //获取模板数据
  const request = {
    cmd: "print",
    requestID: Date.parse(new Date()),
    version: "1.0",
    task: {
      taskID,
      preview: false,
      name: printMachine.value,
      needTopLogo: false,
      needBottomLogo: false,
      autoPageSize: true,
      autoOrientation: true,
      paperSize: {
        width: tempData.width,
        height: tempData.height,
      },
      previewType: "pdf",
      documents: [
        {
          documentID: "",
          contents: [printObj],
        },
      ],
    },
  };
  await printStore.send(JSON.stringify(request));
}
</script>

<style scoped lang="scss"></style>
